package org.itboys.admin.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import org.itboys.admin.entity.AdminOrg;
import org.itboys.mongodb.core.MongoDataSource;
import org.springframework.stereotype.Service;

/**
 * 组织的service层
 * @author WeiSky
 *
 */
@Service
public class AdminOrgService extends BaseAdminService<AdminOrg, Long>{
	/**
	 * 
	 */
	private static final long serialVersionUID = 3835978431001056288L;
	//public static final String PATH_SPLIT = "/";
	@Resource(name="adminDS")
	private MongoDataSource ds;
	
	@Override
	protected MongoDataSource getMongoDataSource() {
		return ds;
	}

	@Override
	protected Class<AdminOrg> getEntityClass() {
		return AdminOrg.class;
	}

	/**
	 *
	 * 获取组织数据。树结构类型。
	 */
	public List<AdminOrg> getOrgTree(){
		Map<String,Object> param =new HashMap<String, Object>();
		param.put("isDeleted",0);
		List<AdminOrg> orgs = super.list(param);

		//组装tree。迭代的方式。能够支持无限级层数
		//先查询出所有根节点
		List<AdminOrg> roots = new ArrayList<AdminOrg>();
		for(AdminOrg org:orgs){
			if(org.getParentId()!=null&&org.getParentId().longValue()==0l){
				roots.add(org);
			}
		}
		recursionTree(orgs,roots);
		return roots;
	}
	//递归子节点。支持无限层级

	/**
	 *
	 * @param alls。递归范围
	 * @param parents。父节点集合
	 * @return
	 */
	public  List<AdminOrg> recursionTree(List<AdminOrg> alls,List<AdminOrg> parents){
		//	List<FinanceProductCategoryDto> parents = new ArrayList<FinanceProductCategoryDto>();
		for(AdminOrg parent:parents){
			List<AdminOrg> children = new ArrayList<AdminOrg>();
			for(AdminOrg child:alls){
				if(isNotZreo(child.getParentId())&&
						parent.getId()==child.getParentId().longValue()){
					children.add(child);
				}
			}


			if(isNotNull(children)) {
				recursionTree(alls, children);
			}
			parent.setChildren(children);

		}
		return parents;
	}
	/**
	 * 修改和新增
	 * @param adminOrg
	 */
	public void saveOrg(AdminOrg adminOrg){
		//AdminSessionHolder.prepareAdminLoginData(adminOrg);
		if(adminOrg.getParentId() == null){

			adminOrg.setParentId(0L);
		}
		if(adminOrg.getId()==0l){

			super.save(adminOrg);

		}else{

			super.updateExceptEmpty(adminOrg.getId(),adminOrg);
		}

	}


	
	

	/**
	 * 删除  isDeleted标为1
	 * @param id
	 */
	public void deleteOrg(Long id){
		update(id, "isDeleted",1);
	}

	public static boolean isNotZreo(Long number){
		if(number!=null&&number!=0)return true;
		return false;
	}
	public static boolean isNotNull(List list){
		boolean flag = false;
		if(list!=null&&list.size()>0){
			flag = true;
		}
		return flag;
	}
}
